import validate from 'wechat-validate'

Page({
  behaviors: [validate],
  data: {
    currentDate: new Date().getTime(),
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
    name: '',
    gender: '',
    mobile: '',
    visitDate: '',
    houseId: '',
    houseInfo: '',
  },
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请检查手机号码是否正确!' },
    ],
    name: [{ required: true, message: '请填写访客姓名!' }],
    houseInfo: [{ required: true, message: '请选择房屋!' }],
    visitDate: [{ required: true, message: '请选择来访日期!' }],
  },
  onLoad() {
    this.getHouseList()
  },
  // 获取房屋列表
  async getHouseList() {
    const res = await wx.http.get('/house')
    this.setData({ houseList: res.data })
  },
  // 选择房屋
  selectHouse(e) {
    this.setData({
      houseId: e.detail.id,
      houseInfo: e.detail.name,
    })
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  async goPassport() {
    if (!this.validate()) return
    const { name, gender, mobile, visitDate, houseId } = this.data
    const { data } = await wx.http.post('/visitor', { name, gender, mobile, visitDate, houseId })

    wx.reLaunch({
      url: '/visitor_pkg/pages/passport/index?id=' + data.id,
    })
  },
  // 选择日期
  confirmDate(e) {
    const d = new Date(e.detail).toLocaleDateString().replaceAll('/', '-')
    this.setData({
      visitDate: d,
      dateLayerVisible: false,
    })
  },
})
